package com.et.machine.manager.vm.goods

import android.annotation.SuppressLint
import android.database.ContentObserver
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.et.api.MachineConfig
import com.et.machine.BuildConfig
import com.et.machine.R
import com.et.machine.convert.machineInfo
import com.et.machine.databinding.FragmentAddGoodsBinding
import com.et.machine.databinding.ItemAddGoodsBinding
import com.et.machine.databinding.ItemAllBoxBinding
import com.et.machine.goods.GoodsHelper
import com.et.machine.goods.globalChannelEntityMap
import com.et.machine.manager.api.*
import com.et.machine.store.ChannelEntity
import com.et.machine.store.DISABLED
import com.et.machine.store.ENABLED
import com.et.machine.store.LACK
import com.et.machine.util.*


class AddGoodsFragment : Fragment() {

    companion object {
        data class Box(var select: Boolean, val box: Int)

        const val BOX_11 = 11
        const val BOX_09 = 9
        const val BOX_08 = 8
        const val BOX_07 = 7
        const val BOX_06 = 6
        const val BOX_01 = 1
        const val BOX_02 = 2
        const val BOX_03 = 3
        const val BOX_04 = 4
        const val BOX_05 = 5
    }

    private lateinit var binding: FragmentAddGoodsBinding

    private val viewModel: AddGoodsViewModel by lazy {
        ViewModelProvider(this).get(AddGoodsViewModel::class.java)
    }
    private val observer: ContentObserver by lazy {
        object : ContentObserver(null) {
            override fun onChange(selfChange: Boolean) {
                super.onChange(selfChange)
                selectedBox?.let {
                    goodsMap.remove(it.box)
                    notifyGoodsInfo(it.box)
                }
            }
        }
    }
    private lateinit var adapterChannel: AdapterUseDiff<ChannelEntity, ItemAddGoodsBinding>
    private lateinit var adapterBox: Adapter<Box, ItemAllBoxBinding>
    private var boxData = mutableListOf<Box>()
    private var selectedBox: Box? = null
    private lateinit var addGoodsDialog: AddGoodsCountDialog
    private val goodsMap: MutableMap<Int, MutableList<ChannelEntity>> = HashMap()
    private val goodsHelper: GoodsHelper
        get() {
            return GoodsHelper.getInstance()
        }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View = FragmentAddGoodsBinding.inflate(inflater, container, false).apply {
        binding = this
    }.root

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initClickEvent()
        initBar()
        initBoxAdapter()
        initChannelAdapter()

    }

    private fun initClickEvent() {
        // back
        binding.layoutTitle.back.setOnClickListener {
            Navigation.findNavController(it).popBackStack()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initBar() {
        // back
        binding.layoutTitle.back.setOnClickListener {
            Navigation.findNavController(it).popBackStack()
        }

        binding.layoutTitle.uuid.text =
            "机器编号：${machineInfo?.uuid}"

        binding.layoutTitle.title.setText(R.string.add_goods_label)
    }

    private fun initBoxAdapter() {
        boxData = viewModel.addBoxList()
        boxData[0].apply {
            select = true
            selectedBox = this
        }
        // layout box
        binding.boxListview.also {
            it.adapter = Adapter(
                { view, _, data ->
                    view.box.text = viewModel.box2Name(data.box)
                    if (data.select) {
                        view.box.setBackgroundResource(R.drawable.radio_button_checked_icon)
                        notifyGoodsInfo(data.box)
                    } else {
                        view.box.setBackgroundResource(R.drawable.radio_button_dischecked_icon)
                    }

                    view.box.setOnClickListener {
                        if (selectedBox != null) {
                            selectedBox!!.select = false
                            data.select = true
                        }
                        selectedBox = data
                        adapterBox.notifyDataSetChanged()
                        notifyGoodsInfo(data.box)
                    }

                }, { inflater, viewGroup ->
                    ItemAllBoxBinding.inflate(inflater, viewGroup, false)
                }, boxData
            ).apply {
                adapterBox = this
            }
            it.layoutManager = LinearLayoutManager(requireContext()).apply {
                orientation = LinearLayoutManager.HORIZONTAL
            }
        }
    }

    private fun initChannelAdapter() {
        binding.recyclerview.layoutManager = GridLayoutManager(requireContext(), 3)

        adapterChannel = AdapterUseDiff({ view, _, goodsInfo ->
            view.run {
                channel.text = goodsInfo.label
                if (goodsInfo.box == 11) {
                    if (goodsInfo.quantity == 0x63) {
                        number.run {
                            setTextColor(Color.BLACK)
                            text = "有货"
                        }
                    } else {
                        number.run {
                            setTextColor(Color.RED)
                            text = "售空"
                        }
                    }
                } else {
                    number.text =
                        if (goodsInfo.quantity == 0x63) "有货" else goodsInfo.quantity.toString()
                    number.setTextColor(Color.BLACK)
                }

                when (goodsInfo.status) {
                    DISABLED -> {
                        goodsStatus.visibility = View.VISIBLE
                        bg.setBackgroundResource(R.drawable.radius_bg1)
                    }
                    ENABLED -> {
                        goodsStatus.visibility = View.GONE
                        bg.setBackgroundResource(R.drawable.radius_bg)
                    }
                    LACK -> {
                        goodsStatus.visibility = View.GONE
                        bg.setBackgroundResource(R.drawable.radius_bg1)
                    }
                }
                if (goodsInfo.image == "No_Image") {
                    image.setImageResource(R.mipmap.wu)
                } else {
                    image.setImageURI(Uri.parse(goodsInfo.image))
                }
                root.setOnClickListener {
                    if (goodsInfo.box == 11) return@setOnClickListener
                    if (goodsInfo.status == DISABLED || goodsInfo.status == LACK) return@setOnClickListener
                    addGoodsDialog =
                        AddGoodsCountDialog(
                            context,
                            goodsInfo
                        ) {
                            uploadChannelEntity(it)
                            number.text =
                                if (goodsInfo.quantity == 0x63) "有货" else goodsInfo.quantity.toString()
                        }
                    addGoodsDialog.show()
                }
            }

        }, { inflater, viewGroup ->
            ItemAddGoodsBinding.inflate(inflater, viewGroup, false)
        })

        binding.recyclerview.adapter = adapterChannel
        requireContext().contentResolver.registerContentObserver(GoodsHelper.GOODS_URI, true, observer)
    }


    private fun uploadChannelEntity(channelEntity: ChannelEntity) {
        when (BuildConfig.FLAVOR) {
            "et" -> {
                goodsHelper.add(
                    channelEntity
                )
                MachineConfig.setGoodsNumber(
                    channelEntity.box,
                    channelEntity.channel,
                    channelEntity.quantity,
                )
            }
            "fs" -> {
            }
            "dc" -> {
            }
        }

    }

    private fun notifyGoodsInfo(id: Int) {
        if (goodsMap[id].isNullOrEmpty()) {
            val goods: MutableList<ChannelEntity> = mutableListOf()
            for (channel in 1..48) {
                if (globalChannelEntityMap[id * 1000 + channel] != null) {
                    goods.add(globalChannelEntityMap[id * 1000 + channel]!!)
                } else {
                    goods.add(ChannelEntity().apply {
                        uid = id * 1000 + channel
                        box = id
                        this.channel = channel
                        label = viewModel.getChannelLabel(box, channel)
                        status = DISABLED
                        image = "No_Image"
                    })
                }

            }
            goods.forEach {
                MachineConfig.setGoodsNumber(it.box, it.channel, it.quantity)
            }
            goodsMap[id] = goods
        }
        adapterChannel.dispatchUpdate(
            DiffUtil.calculateDiff(
                DiffCallBack(adapterChannel.data, goodsMap[id]!!),
                true
            ), goodsMap[id]!!
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        requireContext().contentResolver.unregisterContentObserver(observer)
    }
}

